package com.httpDemo.controller;

import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.httpDemo.doMain.Employee;

import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore // 忽略该api
@Controller
@RequestMapping(value = "/", produces = "application/json;charset=utf-8")
public class IndexController {

	@Autowired
	private Employee employee;

	/**
	 * 测试thymeleaf模板的使用，页面是hello.html
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("hello")
	public String hello(Model model, HttpServletRequest request) {
		model.addAttribute("employee", employee);
		// 向三大作用域中赋值复制，model的作用域同request
		HttpSession session = request.getSession();// 获取session
		ServletContext context = request.getServletContext();// 获取context
		request.setAttribute("key", "request-value");// 向request作用域中赋入key值
		session.setAttribute("key", "session-value");// 向session作用域中赋入key值
		context.setAttribute("key", "context-value");// 向context作用域中赋入key值
		return "hello";
	}

	@RequestMapping("hello2")
	public String hello2(Model model, String name, String age) {
		model.addAttribute("name", name);
		model.addAttribute("age", age);
		return "hello2";
	}

	/**
	 * 如果要调用jsp，需要在pom.xml中将thymeleaf依赖注释掉。
	 * 如果要使用thymeleaf，需要在/gzp/templates/下加上hellojsp.html。
	 * 测试视图控制器和格式化器，代码在MyWebConfig.addViewControllers和MyWebConfig.addFormatters。
	 * 配置文件是application.yml。
	 * 
	 * @param brith
	 * @return
	 */
	@RequestMapping("hellojsp")
	public String hellojsp(@DateTimeFormat(pattern = "yyyy-MM-dd") Date brith, Integer age) {
		System.out.println("brith:" + brith);
		System.out.println("age:" + age);
		return "hellojsp";
	}

	/**
	 * 测试转化器，代码在MyWebConfig.configureMessageConverters、Employee.java
	 * 
	 * @return
	 */
	@RequestMapping("getEmployee")
	@ResponseBody
	public Employee getEmployee() {
		return employee;
	}

}
